import React, {Component} from 'react'


import {
    DeviceEventEmitter,
    Image,
    ListView,
    RefreshControl,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from "react-native";
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import PerformancePage from "./PerformancePage";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from "../../../res/language/i18n";
import MatrixSubBCPage from "./MatrixSubBCPage";
import SubAccountsPage from "./SubAccountsPage";
import RegisterIBMThreePage from "../../common/register/RegisterIBMThreePage";
import AlertDialog from "../../../custom/AlertDialog";


const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2,
});
export default class MatrixPlanPage extends Component {

    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();
        this.country = '';

        this.planNamesData = [
            {name: I18n.t('b.ActivatedBusiness'), color: 'black', value: null, valueText: 0},
            {name: I18n.t('b.noQualifiedBusinessCenters'), color: '#747474', value: [], valueText: 0},
            {name: I18n.t('b.qualifiedBusinessCenters'), color: '#D2D2D2', value: [], valueText: 0},
            // {name: I18n.t('default.newRegistrants'), color: '#b1b1b1', value: null, valueText: 0},
        ];


        this.menuData = [
            I18n.t('b.businessCenter'),
            I18n.t('default.identity'),
            I18n.t('b.leftVolume'),
            I18n.t('b.rightVolume'),
            I18n.t('b.leftRollover'),
            I18n.t('b.rightRollover'),
            I18n.t('b.leftHistoryVolume'),
            I18n.t('b.rightHistoryVolume'),
            I18n.t('b.activationDate')
        ];

        this.state = {
            isLoading: false,
            alertVisible: false,
            plansData: [],
            userData: this.props.userData,
            usersData: [],
            planPerformanceValue: 3123,
        };
    }

    componentDidMount() {
        this.setUsersData(this.props.MatrixPlanData);
    }

    componentWillUnmount() {
        this.iparNetwork = null;
        this.country = null;
        this.planNamesData = []
    }

    /**
     * 获取摸个用户的子账号
     */
    onLoadData() {
        this.setState({
            isLoading: true
        });


        let mainUId = this.state.userData ? this.state.userData.main_user_id : '';
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'getSubAccount?', 'main_user_id=' + mainUId + '&rank=5')
            .then((result) => {
                if (result.code === 200) {
                    this.setUsersData(result.data)
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                    this.setState({
                        isLoading: false
                    });
                }

            })
            .catch((error) => {
                this.setState({
                    isLoading: false
                });

                DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                console.log('MatrixPlanPage-----onLoadData--error: ', error);
            })
    }


    /**
     * setUsersData
     * @param usersData
     */
    setUsersData(data) {
        if (!data) return;
        let length = data.length;
        for (let i = 0; i < length; i++) {
            if (data[i].is_ibm === 1) {
                this.planNamesData[1].value.push(data[i]);
            } else {
                this.planNamesData[2].value.push(data[i]);
            }
        }
        this.planNamesData[0].valueText = length;
        this.planNamesData[1].valueText = this.planNamesData[1].value.length;
        this.planNamesData[2].valueText = this.planNamesData[2].value.length;

        this.setState({
            isLoading: false,
            usersData: data,
        });
    }


    renderPlanLable(rowData, index) {

        return (<TouchableOpacity
            onPress={() => this.planOnClick(rowData, index)}
            style={[StyleUtils.justifySpace, {marginBottom: 22}]}>
            <View style={{width: 22, height: 22, backgroundColor: rowData.color}}/>
            <Text style={[styles.planLable, StyleUtils.smallFont]}>{rowData.name}</Text>
            <Text style={[{fontSize: 16, color: 'black'}, StyleUtils.smallFont]}>{rowData.valueText}</Text>
        </TouchableOpacity>)
    }


    renderMenuTitle() {
        return (<View style={StyleUtils.justifySpace}>

                {this.menuData.map((item, i) => {
                    return <View style={[StyleUtils.center, styles.menuTitle]}>
                        <Text
                            numberOfLines={2}
                            style={[{
                                color: 'white',
                                fontSize: 10,
                                textAlign: 'center',
                                paddingLeft: 4,
                                paddingRight: 4
                            }, StyleUtils.smallFont]}>{item}</Text>
                    </View>

                })}

            </View>
        )
    }


    /**
     *
     */
    planOnClick(item, index) {
        this.props.navigator.push({
            component: SubAccountsPage,
            name: 'SubAccountsPage',
            params: {
                users: (item ? item.value : null) || this.state.usersData,
                title: item ? item.name : null
            }
        })
    }

    onItemClick(dataArray, position) {
        this.props.navigator.push({
            component: MatrixSubBCPage,
            name: 'MatrixSubBCPage',
            params: {
                usersData: dataArray,
                selectDataIndex: position,
            }
        })

    }


    renderMenuViews(rowData, index) {
        return <TouchableOpacity
            onPress={() => {
                this.onItemClick(this.state.usersData, index)
            }}
            style={[StyleUtils.justifySpace]}>

            {this.menuData.map((item, i) => {

                let text = 0;
                switch (i) {
                    case 0:
                        text = rowData.rand_id;
                        break;
                    case 1:
                        text = rowData.user_level ? rowData.user_level.level_name : '';
                        break;
                    case 2:
                        text = (rowData.left_total_group_pv || 0).toFixed(2);
                        break;
                    case 3:
                        text = (rowData.right_total_group_pv || 0).toFixed(2);
                        break;
                    case 4:
                        text = (rowData.left_balance || 0).toFixed(2);
                        break;
                    case 5://left_balance
                        text = (rowData.right_balance || 0).toFixed(2);
                        break;
                    case 6:
                        text = (rowData.left_history_total_pv || 0).toFixed(2);
                        break;
                    case 7:
                        text = (rowData.right_history_total_pv || 0).toFixed(2);
                        break;
                    case 8://right_balance
                        text = rowData.active_time && rowData.active_time.substring(0, 11);
                        break;

                }


                return <View style={[StyleUtils.center, styles.menuTitle, {
                    height: 32,
                    backgroundColor: index % 2 === 0 ? "white" : '#f0f0f0'
                }]}>
                    <Text
                        numberOfLines={2}
                        style={[{
                            color: 'black',
                            fontSize: 10,
                            textAlign: 'center',
                            paddingLeft: 4,
                            paddingRight: 4
                        }, StyleUtils.smallFont]}>{text}</Text>
                </View>

            })}

        </TouchableOpacity>
    }


    startBusiness(userInfo) {
        if (userInfo.is_open_account5 > 0) {
            this.props.navigator.push({
                component: RegisterIBMThreePage,
                name: 'RegisterIBMThreePage',
                params: {
                    selectPlan: {rank: 5, rank_name: this.props.title}
                }
            })
        } else {
            this.setState({
                alertVisible: true,
            });
        }

    }

    render() {
        let props = this.props;

        //奖金
        let _bonus = 0;
        if (props.rewardStatisticsData) {
            _bonus = props.rewardStatisticsData.rank['5'].pv
        }

        let userData = this.state.userData;
        let contentView = (userData && userData.open_plan && (userData.open_plan + '').indexOf('5') !== -1 ? <View>
                    <View style={{padding: 20}}>


                        {ViewUtils.getButton(I18n.t('b.checkDetails'), () => {
                            this.planOnClick(null, 0);
                        }, styles.topBtnStyle, {color: 'black'})}


                        <Text style={{
                            fontSize: 18,
                            color: 'black',
                            marginTop: 36,
                            textAlign: 'center',
                            width: '100%'
                        }}>{I18n.t('b.estimatedPV')}</Text>


                        <PerformancePage
                            value={_bonus}
                            type={0}
                        />


                        {this.planNamesData.map((item, i) => {
                            return this.renderPlanLable(item, i);
                        })}
                    </View>
                    {this.state.usersData.length > 0 ? <ScrollView
                        horizontal={true}>
                        <View>
                            {this.renderMenuTitle()}
                            <ListView
                                renderRow={(rowData, sectionID, rowID) => this.renderMenuViews(rowData, rowID)}
                                dataSource={ds.cloneWithRows(this.state.usersData)}
                            />
                        </View>

                    </ScrollView> : null}

                    <View style={{padding: 16}}>
                        {ViewUtils.getButton(I18n.t('b.activateBusiness'), () => {
                            this.startBusiness(userData)
                        }, {marginTop: 48, height: 42})}
                    </View>
                </View> :
                <View style={[StyleUtils.center, {padding: 16}]}>
                    <Text style={{textAlign: 'center'}}>
                        You have not subsribed to this plan yet.Subscribe now?
                    </Text>
                    {ViewUtils.getButton('Subscribe', () => {
                        this.startBusiness(userData)
                    }, [styles.topBtnStyle, {marginTop: 38}], {color: 'black'})}
                </View>
            )
        ;

        return (<View style={StyleUtils.flex}>

            <Navigation
                titleImage={require('../../../res/images/ic_ipar_logo.png')}
                onClickLeftBtn={() => props.navigator.pop()}/>

            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isLoading}
                        onRefresh={() => this.onLoadData()}
                    />
                }
            >

                {ViewUtils.getTitleView(props.title, I18n.t('b.allAboutMyMatrix'))}

                {contentView}

            </ScrollView>


            {/*<LoadingView visible={this.state.isLoading}/>*/}
            <AlertDialog
                contentTv={I18n.t('b.oppsStartNewBusiness')}
                singleBtnOnclick={() => {
                    this.setState({
                        alertVisible: false
                    })
                }}
                visible={this.state.alertVisible}
                requestClose={() => {
                    this.setState({
                        alertVisible: false
                    })
                }}/>
        </View>)
    }


}

const styles = StyleSheet.create({


    topBtnStyle: {
        backgroundColor: 'white',
        borderWidth: 1,
        height: 42,
        borderColor: '#c8c8c8'
    },

    planLable: {
        borderColor: 'black',
        flex: 1,
        paddingLeft: 8,
        textAlign: 'left'
    },
    reentryViewStyle: {
        borderTopWidth: 1,
        borderBottomWidth: 1,
        borderColor: '#e7e7e7',
        marginTop: 32,
        paddingTop: 16,
        paddingBottom: 16,

    },

    circularText: {
        color: 'white',
        textAlign: 'center',
    },

    menuTitle: {
        width: 88,
        height: 42,
        backgroundColor: 'black'
    },


});